var express = require("express");
var fs = require("fs");
var marked = require("marked");
var app = express();
var nunjucks = require("nunjucks");
var mysql = require("mysql");
var bodyParser = require('body-parser');
var _ = require("ramda");
var sql = require("./kit/sql.js");
var sswdRouter = require("./router/sswd.js");
var reqagent = require('superagent')


// SQLString -> (Error -> Rows -> Fields) -> ()
var esql = sql.esql
// SQL String -> [a] -> (Error -> Rows -> Fields) -> ()
var esqlp = sql.esqlp


nunjucks.configure('view', {
    autoescape: true,
    express: app,
    noCache:process.env.NOCACHE != "true"
});


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());
app.use(express.static("./static"));
app.use("/sswd",sswdRouter)

app.use("/zhihu/:key",function(req,res){
  res.append('accept-ranges','bytes')
  res.append('content-type','image/png')
  res.append('Expires','Sat, 28 Apr 2020 10:11:23 GMT')
  res.append('Cache-Control','max-age=131536000')
  reqagent
  .get('https://pic4.zhimg.com/'+ req.params.key)
  // .set(':authority', 'pic4.zhimg.com')
  // .set(':method', 'get')
  // .set(':scheme', 'https')
  .set('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36')
  .set('referer', 'https://zhuanlan.zhihu.com/p/26173651')
  // .set(':path', '/v2-82e6c243a850fcdc4ac2a710133fffd3_r.png')
  .pipe(res)
})
app.get("/sitemap.txt",function(req,res){
  // String -> Boolean
  function hanzi(a){
    return a == "," ? true
    : a == "." ? true
    : a >= "A" && a <= "z" ? true
    : a.charCodeAt(0) > 1000 ? true
    : false
  }
  esql("select pathid,banner,content,title,tag_1,tag_2,tag_3,c_date from blog_t order by c_date desc limit 3000",function(err,rows){
    if(err){
      res.send("404");
    }else{
      res.set({
        'Content-Type': 'text/plain'
      })
      var r = [];
      _.forEach(function(item){
        r.push("http://www.diqye.com/"+item.pathid+".html")
      },rows)
      res.send(r.join("\n"))
      // res.render("sitemap.html",{
      //   list:rows,
      //   f:{
      //     description:_.pipe(_.filter(hanzi),_.take(500),_.join('')),
      //   }
      // });
    }
  })
});
app.get("/",function(req,res,next){
  // String -> String
  function getOrEmpty(o){
    return o == null ? "" : o;
  }
  // Row {} -> String
  function format(item){
    return getOrEmpty(item.tag_1) + " " + getOrEmpty(item.tag_2) + " " + getOrEmpty(item.tag_3);
  }
  if(req.hostname == 'repl.diqye.com'){
    res.render('repl.html')
  }else if(req.hostname == '127.0.0.1'){
    res.render('repl.html')
  }else{
    esql("select pathid,banner,title,tag_1,tag_2,tag_3,c_date from blog_t order by c_date desc limit 50",function(err,rows){
      if(err){
        res.send("404");
      }else{
        res.render("index.html",{
          list:rows,
          f:{
            format:format
          }
        });
      }
    })
  }
});

app.get("/edit/new",function(req,res){
  res.render("edit.html",{});
});
app.post("/edit/new",function(req,res){
  // String -> String
  function emptyToNull(o){
    return o==null||o.trim() == "" ? null : o;
  }
  if(req.body.password != 'diqye-password'){
    res.render("edit.html",{
      hasError:'请输入正确的密码',
      body:req.body
    })
    return
  }
  esqlp("insert into blog_t(pathid,title,banner,content,c_date,tag_1,tag_2,tag_3) values(?,?,?,?,now(),?,?,?)",
  [
    req.body.pathid,
    req.body.title,
    req.body.banner,
    req.body.content,
    emptyToNull(req.body.tag.split(" ")[0]),
    emptyToNull(req.body.tag.split(" ")[1]),
    emptyToNull(req.body.tag.split(" ")[2])
  ],
  function(err,rows,fields){
    if(err){
      res.render("edit.html",{
        hasError:err,
        body:req.body
      });
    }else {
      res.redirect("/"+req.body.pathid+".html");
    }
  });
});
app.get("/edit/:pathid",function(req,res){
  // String -> String
  function getOrEmpty(o){
    return o == null ? "" : o;
  }
  // String -> String
  function emptyToNull(o){
    return o==null||o.trim() == "" ? null : o.trim();
  }
  esqlp("select pathid,banner,title,content,tag_1,tag_2,tag_3,c_date from blog_t where  pathid = ? ;",
  [req.params.pathid],
  function(err,rows){
    if(err){
      res.render("edit.html",{hasError:err});
    }else if(rows==null||rows.length == 0){
      res.render("edit.html",{hasError:"该文章不存在或者已被删除!"});
    }else{
      var item = rows[0];
      item.tag = getOrEmpty(item.tag_1) + " " + getOrEmpty(item.tag_2) + " " + getOrEmpty(item.tag_3);
      item.tag = item.tag.trim();
      res.render("edit.html",{body:item});
    }
  });
});
app.post("/edit/:pathid",function(req,res){
  // String -> String
  function emptyToNull(o){
    return o==null||o.trim() == "" ? null : o.trim();
  }
  if(req.body.password != 'diqye-password'){
    res.render("edit.html",{
      hasError:'请输入正确的密码',
      body:req.body
    })
    return
  }
  esqlp("update blog_t SET pathid = ?,banner=?,title=?,content=?,tag_1=?,tag_2=?,tag_3=? where pathid = ? ;",
  [
    req.body.pathid,
    req.body.banner,
    req.body.title,
    req.body.content,
    emptyToNull(req.body.tag.split(" ")[0]),
    emptyToNull(req.body.tag.split(" ")[1]),
    emptyToNull(req.body.tag.split(" ")[2]),
    req.params.pathid
  ],
  function(err,rows,fields){
    if(err){
      res.render("edit.html",{
        hasError:err,
        body:req.body
      });
    }else {
      res.redirect("/"+req.body.pathid+".html");
    }
  });
})
app.get(/([a-z|0-9|\-]+).html/,function(req,res,next){
  // String -> String
  function getOrEmpty(o){
    return o == null ? "" : o;
  }
  // String -> String
  function emptyToNull(o){
    return o.trim() == "" ? null : o.trim();
  }
  // String -> Boolean
  function hanzi(a){
    return a == "," ? true
    : a == "." ? true
    : a >= "A" && a <= "z" ? true
    : a.charCodeAt(0) > 1000 ? true
    : false
  }
  // UAString -> Boolean
  function isWX(ua){
    return ua.indexOf("MicroMessenger") != -1;
  }
  // UAString -> Boolean
  function isM(ua){
    return ua.indexOf("Mobile") != -1;
  }
  var f = {
    //String -> String
    description:_.pipe(_.filter(hanzi),_.take(200),_.join('')),
    isWX:isWX,
    isM:isM
  }
  esqlp("select pathid,banner,title,content,tag_1,tag_2,tag_3,c_date from blog_t where  pathid = ? ;",
  [req.params[0]],
  function(err,rows){
    if(err){
      res.send(err);
    }else if(rows==null||rows.length == 0){
      res.send("该文章不存在或者已被删除<a href='/'>返回列表页</a>");
    }else{
      var item = rows[0];
      item.tag = getOrEmpty(item.tag_1) + " " + getOrEmpty(item.tag_2) + " " + getOrEmpty(item.tag_3);
      item.tag = item.tag.trim();
      if(item.tag_1 == 'mpt'){
        res.render("mpt.html",{
          md:JSON.stringify(encodeURIComponent(item.content)),
          title:item.title
        })
      }else{
        res.render("blog.html",{
          md:marked(item.content||""),
          content:item.content,
          title:item.title,
          tag:item.tag,
          banner:item.banner,
          c_date:item.c_date,
          ua:req.headers["user-agent"],
          query:req.query,
          f:f
        });
      }
    }
  });
});


app.listen(process.env.VCAP_APP_PORT || 7777,function(){
  console.log("diqye-blog is stared port is 7777");
});
